

#include "AsyncSerial.h"
#include "util/Util.h"
#include "SerialOps.h"

AsyncSerial::AsyncSerial()
{
	m_PortName = "/dev/ttySAC2";
	m_baudrate = 9600;
	m_databits = 8;
	m_stopbits = 1;
	m_parity = 'n';
}

AsyncSerial::~AsyncSerial()
{
	CloseFD( );
}


bool AsyncSerial::Connect( const char * Address )
{
	std::vector<std::string> vAddress = SplitString( Address, ":");

	switch(vAddress.size())
	{
	case 5:
		m_parity	= vAddress[4][0];
	case 4:
		m_stopbits	= atol(vAddress[3].c_str());
	case 3:
		m_databits	= atol(vAddress[2].c_str());
	case 2:
		m_baudrate	= atol(vAddress[1].c_str());
	case 1:
		m_PortName	= vAddress[0];
	}

	m_fd = SerialOps::OpenDevice(m_PortName.c_str() );

	if ( INVALID_FD == m_fd) {
		return false;
	} else {
		SerialOps::SetSpeed(m_fd, m_baudrate);
		SerialOps::SetParity(m_fd, m_databits, m_stopbits, m_parity);
		this->OnConnect();
		return true;
	}
}

bool AsyncSerial::CloseFD() 
{
	SerialOps::CloseFD(m_fd);
	return true;
}

int AsyncSerial::_RawReadData(char* pBuff, uint32 nBuffLen )
{
	int32 nRead = SerialOps::Read( m_fd, pBuff, nBuffLen );
	return nRead;
}

int AsyncSerial::_RawWriteDate(char* pBuff, uint32 nDataLen )
{
	int hasWrite = 0;
	hasWrite = SerialOps::Write(m_fd, pBuff, nDataLen);
	return hasWrite ;
}


bool AsyncSerial::_NonblockingFD()
{
	//
	return true;
}
